package com.atcjx.config;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.atcjx.MyUtils.JwtUtils;
import com.atcjx.MyUtils.ResultFactory;
import com.atcjx.exception.UserException;
import com.atcjx.exception.exceptionEnum;
import com.atcjx.pojo.Article.Enum.UserRoleEnum;
import com.atcjx.pojo.JwtConstants;
import com.atcjx.pojo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import jdk.nashorn.internal.runtime.options.Options;
import org.springframework.http.server.PathContainer;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName LoginInterceptor.java
 * @Description TODO
 * @createTime 2021年09月24日 19:12:00
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    /*
     * 处理请求前
     * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //根据请求头获取请求的token
        String token=request.getHeader(JwtConstants.TOKEN_HEADER);
        //判断是否为空  或token不是规定前缀
        if(StringUtils.isEmpty(token)||!token.startsWith(JwtConstants.TOKEN_PREFIX))
        {
            throw new UserException(exceptionEnum.NotLogin.getMsg(),exceptionEnum.NotLogin.getCode());
        }
        //将token前缀替换为空
        token=token.replace(JwtConstants.TOKEN_PREFIX, StrUtil.EMPTY);
        //token已经过期
        if(JwtUtils.isTokenExpired(token)){
            throw new UserException(exceptionEnum.LongTimeLogin.getMsg(),exceptionEnum.LongTimeLogin.getCode());
        }
        Claims claims=JwtUtils.getTokenBody(token);
        String[] roles = Optional.ofNullable(claims.get(JwtConstants.ROLE_CLAIMS))
                .map(r -> r.toString().split(","))
                .orElse(new String[0]);
        //没有访问权限
        if(!ArrayUtil.contains(roles, UserRoleEnum.ADMIN.getValue())){
            throw new UserException(exceptionEnum.BadLogin.getMsg(),exceptionEnum.BadLogin.getCode());
        }
        return true;
    }
    //返回json格式错误信息
    private static void setReturn(HttpServletResponse response, Integer code, String msg) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        //UTF-8编码
        httpResponse.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        Result result = ResultFactory.failureWithData(code, msg);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(result);
        httpResponse.getWriter().print(json);
    }
}
